package controllers

import (
	"errors"
	m "git.oschina.net/liukexing/RbacManager/models/center"
	. "git.oschina.net/liukexing/RbacManager/models/lib"

	"github.com/astaxie/beego"
)

type RootController struct {
	CommonController
}

func (r *RootController) URLMapping() {
	r.Mapping("Index", r.Index)
	r.Mapping("Login", r.Login)
	r.Mapping("CheckUser", r.CheckUser)
	r.Mapping("LoginOut", r.LoginOut)
	r.Mapping("Error", r.Error)
	r.Mapping("NotAccess", r.NotAccess)
}

// @router / [get]
func (r *RootController) Index() {
	r.Data["Title"] = "网站导航"
	usrid := r.GetSession("userid")
	if usrid == nil {
		links := []struct {
			Image string
			Title string
			Des   string
			Link  string
		}{
			{"Book", "登录", "用户登录验证test", r.URLFor("RootController.Login")},
		}
		r.Data["links"] = links
	} else {
		links := []struct {
			Image string
			Title string
			Des   string
			Link  string
		}{
			{"Book", "后台管理", "后台管理-管理用户", r.URLFor("UserController.Index")},
		}
		r.Data["links"] = links
	}
}

// @router /login [get]
func (r *RootController) Login() {
	r.Data["Title"] = "登录"
}

// @router /loginout [get]
func (r *RootController) LoginOut() {
	r.DestroySession()
	r.Redirect(r.URLFor("RootController.Index"), 302)
}

// @router /accessuser [post]
func (r *RootController) CheckUser() {
	result := true
	flash := beego.NewFlash()
	loginname := r.GetString("loginname")
	loginpass := r.GetString("loginpass")
	if loginname == "" || loginpass == "" {
		result = false
		flash.Warning("用户名和密码不能为空！")
	} else {
		user, err := CheckLogin(loginname, loginpass)
		if err == nil {
			r.SetSession("userid", user.Id)
			r.SetSession("username", user.Nickname)
			flash.Notice("欢迎" + user.Nickname + ",登录系统")
		} else {
			result = false
			flash.Error(err.Error())
		}
	}
	flash.Store(&r.Controller)
	if result {
		r.Redirect(r.URLFor("RootController.Index"), 302)
	} else {
		r.Redirect(r.URLFor("RootController.Login"), 302)
	}

}

// @router /error [get]
func (r *RootController) Error() {

}

//check login
func CheckLogin(username string, password string) (user m.User, err error) {
	user = m.GetUserByUsername(username)
	if user.Id == 0 {
		return user, errors.New("用户不存在")
	}
	if user.Password != Pwdhash(password) {
		return user, errors.New("密码错误")
	}
	return user, nil
}

// @router /notaccess [get]
func (r *RootController) NotAccess() {

}
